package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

// 实现博客详情页
@WebServlet("/blog2")
public class BlogDetailServlet extends HttpServlet {
    // 构造 json 对象
    private ObjectMapper objectMapper  = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf8");
        BlogDao blogDao = new BlogDao();
        // 先获取 id，判断有无，没有就回去全列表
        String pa = req.getParameter("blogId");
        if(pa == null) {
            // 如果不存在，就获取博客所有列表
            List<Blog> blogs = blogDao.selectAll();
            // 把 blogs 对象转成 JSON 格式
            String respJon = objectMapper.writeValueAsString(blogs);
            resp.getWriter().write(respJon);
        }else {
            // 如果存在，就获取此博客详情页
            int blogId = Integer.parseInt(pa);
            Blog blog = blogDao.selectOne(blogId);
            String respJon = objectMapper.writeValueAsString(blog);
            resp.getWriter().write(respJon);
        }
    }
}
